/**
 * 生成uuid
 * @returns {*}
 */
export function generateUUID () {
    return ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, (c) => (c ^ (crypto.getRandomValues(new Uint8Array(1))[0] & (15 >> (c / 4)))).toString(16))
}

/**
 * style去掉单位，单位只能是px
 * @param object
 */
export function reduceStyleUnit (object) {
    if (!object) return {}
    const styleObject = JSON.parse(JSON.stringify(object))
    for (let attribute in styleObject) {
        const value = styleObject[attribute]
        if (typeof value === 'string' && value.includes('px')) {
            styleObject[attribute] = parseInt(value)
        }
    }
    // 顺手加上lineHeight
    styleObject.lineHeight = 1
    return styleObject
}

/**
 * style样式处理成可显示格式
 * @param object
 * @returns {{}|*}
 */
export function addStyleUnit (object) {
    if (!object) return {}
    const attributes = ['fontSize', 'paddingLeft', 'paddingTop', 'paddingRight', 'paddingBottom', 'letterSpacing', 'borderRadius', 'borderWidth']
    const styleObject = JSON.parse(JSON.stringify(object))
    for (let attribute in styleObject) {
        const value = styleObject[attribute]
        if (attributes.includes(attribute)) {
            styleObject[attribute] = value + 'px'
        }
    }
    // 顺手加上lineHeight
    styleObject.lineHeight = 1
    let { TX = 0, TY = -10 } = object || {}
    if (!(String(TX).includes('%'))) {
        TX = TX + 'px'
    }

    if (!(String(TY).includes('%'))) {
        TY = TY + 'px'
    }
    styleObject.transform = `translate(${TX}, ${TY})`
    delete styleObject.TX
    delete styleObject.TY
    return styleObject
}

/**
 * 通过id查找是否存在marker
 */
export function hasMarkerById (markerPlugin, id) {
    if (!markerPlugin) return false
    try {
        const marker = markerPlugin.getMarker(id)
        if (marker) return true
    } catch (e) {
        return false
    }
}

/**
 * 获取图片尺寸
 * @param url
 * @param callback
 */
export function getImageSize (url, callback) {
    const img = new Image()
    img.onload = function () {
        callback({
            width: img.naturalWidth, height: img.naturalHeight
        })
    }
    img.src = url
}

/**
 * 提取出translate(Xpx,Ypx) 的 X 和 Y
 */
export function filterTranslateXY (transform) {
    let x = 0, y = 10
    if (transform) {
        const matches = transform.match(/translate\(([^,]+),\s*([^)]+)\)/)
        if (matches) {
            // 考虑下%和px
            const v1 = matches[1]
            const v2 = matches[2]

            if (v1.includes('%') || v1.includes('calc')) {
                x = v1
            } else {
                x = parseFloat(v1)
            }

            if (v2.includes('%') || v2.includes('calc')) {
                y = v2
            } else {
                y = parseFloat(v2)
            }
        }
    }

    return {
        x: x,
        y: y
    }

}

/**
 * todo 部分情况不准,待研究
 * @param vertices
 * @returns {number[]}
 */
export function calculateCentroid (viewer, vertices) {

    // const vertices = points.map((point) => {
    //     const {x, y} = viewer.dataHelper.sphericalCoordsToViewerCoords({yaw: point[0], pitch: point[1]});
    //     return [x, y];
    // });

    let xc = 0
    let yc = 0
    const len = vertices.length

    vertices.forEach((point) => {
        xc += point[0]
        yc += point[1]
    })

    const centroidX = xc / len
    const centroidY = yc / len

    // // 计算多边形的面积
    // let area = 0;
    // let centroidX = 0;
    // let centroidY = 0;
    // const n = vertices.length;
    //
    // for (let i = 0; i < n; i++) {
    //     const x0 = vertices[i][0];
    //     const y0 = vertices[i][1];
    //     const x1 = vertices[(i + 1) % n][0];
    //     const y1 = vertices[(i + 1) % n][1];
    //     const cross = x0 * y1 - x1 * y0;
    //     area += cross;
    //     centroidX += (x0 + x1) * cross;
    //     centroidY += (y0 + y1) * cross;
    // }
    // area /= 2;
    // centroidX /= (6 * area);
    // centroidY /= (6 * area);
    // const {yaw, pitch} = viewer.dataHelper.viewerCoordsToSphericalCoords({x: centroidX, y: centroidY});
    return [centroidX, centroidY]
}

/**
 * 通过parent_id获取树形结构
 * @param data
 * @returns {*}
 */
export function convertToTree (data) {
    // 创建一个映射表，方便快速查找节点
    const map = {}
    data.forEach(item => {
        map[item.id] = { ...item, children: [] }
    })

    // 构建树结构
    const tree = []
    data.forEach(item => {
        if (item.parent_id === 0) {
            // 顶级节点
            tree.push(map[item.id])
        } else {
            // 子节点，添加到父节点的 children 中
            const parent = map[item.parent_id]
            if (parent) {
                parent.children.push(map[item.id])
            }
        }
    })

    return tree
}

/**
 * 根据key和value过滤树结构
 * @param tree
 * @param key
 * @param value
 * @param exclude
 * @returns {*}
 */
export function filterTreeByKeyValue (tree, key, value, exclude) {
    const treeList = tree.reduce((acc, node) => {
        // 如果当前节点符合key-value条件，或者它有符合条件的子节点，则保留该节点
        if (node[key] == value || (node.children && node.children.length > 0)) {
            const newNode = { ...node } // 创建新对象避免直接修改原数据
            // 递归过滤子节点
            if (newNode.children && newNode.children.length > 0) {
                newNode.children = filterTreeByKeyValue(newNode.children, key, value)
                // 只有当子节点中存在匹配项时，才添加当前节点
                if (newNode.children.length > 0 || newNode[key] == value && value != exclude) {
                    acc.push(newNode)
                }
            } else if (newNode[key] == value) {
                // 当前节点没有子节点但符合key-value条件
                acc.push(newNode)
            }
        }
        return acc
    }, [])
    console.log(treeList)
    return treeList
}


/**
 * 判断是否为图片
 * @param path
 * @returns {boolean}
 */
export const isImg = (path) => {
    return /\.(png|jpg|jpeg|gif)$/i.test(path)
}

/**
 * 判断是否为视频
 */
export const isVideo = (path) => {
    return /\.(mp4|webm|ogg|mov)$/i.test(path)
}